import json
from selenium import webdriver
from selenium.webdriver.common.desired_capabilities import DesiredCapabilities
import time
import re
import openpyxl
class score():
    def __init__(self):
        pass
    def openWEB(self):
        desired_capabilities = DesiredCapabilities.CHROME
        desired_capabilities["pageLoadStrategy"] = "none"
        option=webdriver.ChromeOptions()
        option.add_argument('--headless')
        option.add_argument("–incognito")
        option.add_argument('--user-agent="Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/84.0.4147.135 Safari/537.36"')
        diver=webdriver.Chrome(options=option)
        return diver
    def save_cookie(self,user):
        self.USERID=user[0]
        self.PASSWORD=user[1]
        diver=self.openWEB()
        diver.get('http://authserver.xju.edu.cn/authserver/login?service=http%3A%2F%2Fehall.xju.edu.cn%2Flogin%3Fservice%3Dhttp%3A%2F%2Fehall.xju.edu.cn%2Fnew%2Findex.html')
        time.sleep(8)
        diver.find_element_by_xpath('//*[@id="username"]').send_keys(self.USERID)
        diver.find_element_by_xpath('//*[@id="password"]').send_keys(self.PASSWORD)
        diver.find_element_by_xpath('//*[@id="casLoginForm"]/p[6]/div/ins').click()
        time.sleep(3)
        diver.find_element_by_xpath('//*[@id="casLoginForm"]/p[5]/button').click()
        time.sleep(5)
        if diver.current_url=='http://ehall.xju.edu.cn/new/index.html':
            diver.get('http://ehall.xju.edu.cn/psfw/sys/pscjcxapp/*default/index.do?')
            time.sleep(5)
            cookie=diver.get_cookies()
            cookies=json.dumps(cookie)
            with open(r'.\file\cookies.txt','w') as f:
                f.write(cookies)
            print('cookie获取完成')
            diver.quit()
            return 1
        else:
            diver.quit()
            return 0
    def calculation(self,str,p):
        if p==0:
            try:
                num=float(str)
            except:
                return 1
            if num>60:
                a=num//10-5
                b=num%10/10
                return a+b
            else:
                return 0
        elif p==1:
            try:
                num=float(str)
            except:
                num=0
            return num
    def page_handle(self,page):
        datalist=[]
        total_XF=0
        total_ZCJ=0
        js_data=re.findall('pre-wrap;">(.*?)</pre>',page)
        dict_data=json.loads(js_data[0])
        N_data=dict_data['datas']['cxxscj']['rows']
        for i in N_data:
            if i not in datalist:
                datalist.append(i)
        for i in datalist:
            total_XF+=self.calculation(i['XF'],1)
        for i in datalist:
            total_ZCJ+=self.calculation(i['ZCJ'],0)*self.calculation(i['XF'],1)/total_XF
        return (total_XF,round(total_ZCJ,2))
    def find(self,XH,XN,XQ):
        self.all_class=[]
        diver=self.openWEB()
            # ---------登录查询页面首----------#
        diver.get('http://ehall.xju.edu.cn/psfw/sys/pscjcxapp/modules/cjcx/cxxscj.do?XSBH='+XH+'&XN='+XN+'&XQ='+XQ+'&pageSize=150&pageNumber=1')
        time.sleep(5)
        with open(r'.\file\cookies.txt','r') as f:
            cookielist=json.loads(f.read())
            for cookies in cookielist:
                diver.add_cookie(cookies)
        diver.get('http://ehall.xju.edu.cn/psfw/sys/pscjcxapp/modules/cjcx/cxxscj.do?XSBH='+XH+'&XN='+XN+'&XQ='+XQ+'&pageSize=150&pageNumber=1')
            # ---------登录查询页面尾----------#
        time.sleep(3)
        # if (diver.current_url!='http://ehall.xju.edu.cn/psfw/sys/pscjcxapp/modules/cjcx/cxxscj.do?XSBH='+XH+'&XN='+XN+'&XQ='+XQ+'&pageSize=150&pageNumber=1'):
        #     print('已有的cookie已失效，正在获取最新cookie，请稍等片刻···')
        #     self.save_cookie(())
        #     # ---------登录查询页面首----------#
        #     with open(r'C:\Users\HUAWEI\Desktop\text\cookies.txt','r') as f:
        #         cookielist=json.loads(f.read())
        #         for cookies in cookielist:
        #             diver.add_cookie(cookies)
        #     diver.get('http://ehall.xju.edu.cn/psfw/sys/pscjcxapp/modules/cjcx/cxxscj.do?XSBH='+XH+'&XN='+XN+'&XQ='+XQ+'&pageSize=150&pageNumber=1')
            # ---------登录查询页面尾----------#
        time.sleep(3)
        data=diver.page_source
        diver.quit()
        js_data=re.findall('pre-wrap;">(.*?)</pre>',data)
        dict_data=json.loads(js_data[0])
        N_data=dict_data['datas']['cxxscj']['rows']
        for i in N_data:
            if i not in self.all_class:
                self.all_class.append(i)
        return self.all_class
        # diver.get('http://authserver.xju.edu.cn/authserver/login?service=http%3A%2F%2Fehall.xju.edu.cn%2Flogin%3Fservice%3Dhttp%3A%2F%2Fehall.xju.edu.cn%2Fnew%2Findex.html')
        # time.sleep(8)
        # diver.find_element_by_xpath('//*[@id="username"]').send_keys(self.USERID)
        # diver.find_element_by_xpath('//*[@id="password"]').send_keys(self.PASSWORD)
        # time.sleep(3)
        # diver.find_element_by_xpath('//*[@id="casLoginForm"]/p[5]/button').click()
        # time.sleep(8)
        # diver.get('http://ehall.xju.edu.cn/psfw/sys/pscjcxapp/*default/index.do?')
        # time.sleep(8)
        # diver.get('http://ehall.xju.edu.cn/psfw/sys/pscjcxapp/modules/cjcx/cxxscj.do?XSBH='+self.XH+'&XN='+self.XN+'&XQ='+self.XQ+'&pageSize=150&pageNumber=1')
        # time.sleep(5)
        # data=diver.page_source
        # diver.quit()
    def find_all(self,XH_list,XN,XQ):
        data_list={}
        diver=self.openWEB()
        # 为添加cookie作准备
        diver.get('http://ehall.xju.edu.cn/psfw/sys/pscjcxapp/modules/cjcx/cxxscj.do?XSBH='+XH_list[0]+'&XN=2019&XQ=1&pageSize=150&pageNumber=1')
        time.sleep(5)
        # 添加cookie信息
        with open(r'.\file\cookies.txt','r') as f:
            cookielist=json.loads(f.read())
            for cookies in cookielist:
                diver.add_cookie(cookies)
        # 携带本地cookie尝试访问
        diver.get('http://ehall.xju.edu.cn/psfw/sys/pscjcxapp/modules/cjcx/cxxscj.do?XSBH='+XH_list[0]+'&XN=2019&XQ=1&pageSize=150&pageNumber=1')
        time.sleep(3)
        # 本地cookie失效处理
        # if (diver.current_url!='http://ehall.xju.edu.cn/psfw/sys/pscjcxapp/modules/cjcx/cxxscj.do?XSBH='+self.USERID+'&XN=2019&XQ=1&pageSize=150&pageNumber=1'):
        #     print('已有的cookie已失效，正在获取最新cookie，请稍等片刻···')
        #     # 获取新cookie并保存本地
        #     self.save_cookie()
        #     # 使浏览器携带新cookie
        #     with open(r'C:\Users\HUAWEI\Desktop\text\cookies.txt','r') as f:
        #         cookielist=json.loads(f.read())
        #         for cookies in cookielist:
        #             diver.add_cookie(cookies)
        # 学年批量查询模式
        if XQ=='0':
            for XH in XH_list:
                # 查询第一学期信息
                diver.get('http://ehall.xju.edu.cn/psfw/sys/pscjcxapp/modules/cjcx/cxxscj.do?XSBH='+XH+'&XN='+XN+'&XQ=1&pageSize=150&pageNumber=1')
                time.sleep(4)
                data1=diver.page_source
                # 查找第二学期信息
                diver.get('http://ehall.xju.edu.cn/psfw/sys/pscjcxapp/modules/cjcx/cxxscj.do?XSBH='+XH+'&XN='+XN+'&XQ=2&pageSize=150&pageNumber=1')
                time.sleep(4)
                data2=diver.page_source
                # 成绩转化统计
                XQ1_data=self.page_handle(data1)
                XQ2_data=self.page_handle(data2)
                total_XF=XQ1_data[0]+XQ2_data[0]
                total_ZCJ=(XQ1_data[1]*XQ1_data[0]/total_XF)+(XQ2_data[1]*XQ2_data[0]/total_XF)
                data_list[XH]=(total_XF,round(total_ZCJ,2))
            diver.quit()
        elif XQ=='1':
            for XH in XH_list:
                diver.get('http://ehall.xju.edu.cn/psfw/sys/pscjcxapp/modules/cjcx/cxxscj.do?XSBH='+XH+'&XN='+XN+'&XQ=1&pageSize=150&pageNumber=1')
                time.sleep(2)
                data1=diver.page_source
                XQ1_data=self.page_handle(data1)
                data_list[XH]=XQ1_data
            diver.quit()
        elif XQ=='2':
            for XH in XH_list:
                diver.get('http://ehall.xju.edu.cn/psfw/sys/pscjcxapp/modules/cjcx/cxxscj.do?XSBH='+XH+'&XN='+XN+'&XQ=2&pageSize=150&pageNumber=1')
                time.sleep(2)
                data1=diver.page_source
                XQ1_data=self.page_handle(data1)
                data_list[XH]=XQ1_data
            diver.quit()
        else:
            print('学期填写错误')
        print(data_list)
        return data_list
    def XQ_point(self,XH,XN,XQ):
        data=self.find(XH,XN,XQ)
        total_XF=0
        total_ZCJ=0
        for i in data:
            total_XF+=self.calculation(i['XF'],1)
        for i in data:
            total_ZCJ+=self.calculation(i['ZCJ'],0)*self.calculation(i['XF'],1)/total_XF
        return ((total_XF,round(total_ZCJ,2)),data)
    def XN_point(self,XH,XN):
        XQ1_data=self.XQ_point(XH,XN,'1')[0]
        XQ2_data=self.XQ_point(XH,XN,'2')[0]
        total_XF=XQ1_data[0]+XQ2_data[0]
        total_ZCJ=(XQ1_data[1]*XQ1_data[0]/total_XF)+(XQ2_data[1]*XQ2_data[0]/total_XF)
        print('第一学期：{0} , 第二学期：{1}'.format(XQ1_data,XQ2_data))
        return (total_XF,round(total_ZCJ,2))
    def text_cookie(self):
        diver=self.openWEB()
        diver.get('http://ehall.xju.edu.cn/new/index.html')
        time.sleep(5)
        with open(r'.\file\cookies.txt','r') as f:
            cookielist=json.loads(f.read())
            for cookies in cookielist:
                diver.add_cookie(cookies)
        diver.get('http://ehall.xju.edu.cn/new/index.html')
        time.sleep(5)
        if diver.current_url=='http://ehall.xju.edu.cn/new/index.html':
            diver.quit()
            return 1
        else:
            diver.quit()
            return 0
    def sort_data(self,XH_list,XN,XQ):
        new_data={}
        list=[]
        dict=self.find_all(XH_list,XN,XQ)
        for i in dict:
            new_data[i]=dict[i][1]
        tuple = zip(new_data.values(),new_data.keys())
        rank=sorted(tuple,reverse=True)
        for i in rank:
            list.append('学号：{0} 绩点：{1}'.format(i[1],i[0]))
        return list
    def import_data(self,route):
        XH_list=[]
        if '.xlsx' in route:
            original_data=openpyxl.load_workbook(route)['Sheet1']
            maxrow=original_data.max_row
            for i in range(2,maxrow+1):
                if str(original_data['A'+str(i)].value) not in XH_list:
                    XH_list.append(str(original_data['A'+str(i)].value))
            return XH_list
        else:
            pass





